package apps.reading.db;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import core.tool.common.StringHelper;

@Service("webSourceService")
public class WebSourceServiceImpl implements WebSourceService{

    @Autowired
	private WebSourceDAO webSourceDAO;
    

    @Autowired
	private FavoriteDAO favoriteDAO;
	
    @Transactional
	public WebSourceBean save(WebSourceBean accountInfo) {
		return webSourceDAO.save(accountInfo);
	}

	public boolean existsTitle(String title) {
		List<WebSourceBean> list=webSourceDAO.findByTitle(title);
		boolean flag=(list!=null && list.size()>0)?true:false;
		return flag;
	}

	public Page<WebSourceBean> findBySourceTypePager(String sourceType,Pageable pageable) {
		return webSourceDAO.findBySourceType(sourceType, pageable);
	}

	public WebSourceBean getById(String id) {
		WebSourceBean webSourceBean=webSourceDAO.findOne(id);
		return webSourceBean;
	}

	public Page<WebSourceBean> findBySourceTypePager(String sourceType,String type, Pageable pageable) {
		return webSourceDAO.findBySourceTypeAndType(sourceType, type, pageable);
	}

	public void addFavorite(FavoriteBean favoriteBean) {
		List<FavoriteBean> list=favoriteDAO.findByUseridAndSourceid(favoriteBean.getUserid(), favoriteBean.getSourceid());
		if(list==null || list.size()==0) {
			favoriteBean.setId(StringHelper.getUUID());
			favoriteBean.setCreatetime(new Date());
			favoriteDAO.save(favoriteBean);			
		}
	}

	public void cancelFavorite(FavoriteBean favoriteBean) {
		List<FavoriteBean> list=favoriteDAO.findByUseridAndSourceid(favoriteBean.getUserid(), favoriteBean.getSourceid());
		if(list!=null && list.size()==1) {
			favoriteDAO.delete(list.get(0).getId());
		}
	}

	public Page<FavoriteBean> findByUserIdPager(String userId, int page,int size) {
		Sort sort=new Sort(Direction.DESC,"createtime");
		PageRequest pageReqeust=new PageRequest(page,size,sort);
		Page<FavoriteBean> pageResult=favoriteDAO.findByUserid(userId, pageReqeust);
		return pageResult;
	}

	public boolean existsFavorite(String resourceId, String userId) {
		List<FavoriteBean> list=favoriteDAO.findByUseridAndSourceid(userId, resourceId);
		boolean flag=(list!=null && list.size()>0)?true:false;
		return flag;
	}

}
